package com.example.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.adapter.MyAdapterTest;
import com.example.adapter.MyQuestionAdapter;
import com.example.android.ArticleTest;
import com.example.android.QuestionTest;
import com.example.androidtest.MyAdapter;
import com.example.androidtest.MyThread;
import com.example.androidtest.R;
import com.example.androidtest.R.id;
import com.example.androidtest.R.layout;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Question_Fragment extends Fragment {
	private MyQuestionAdapter adapter;
	private ViewPager viewpager;
	private ArrayList<View> data;
	private Handler handler;
	private String url = "http://www.mengxianyi.net/one/question.json";
	private String result;
	private ArrayList<QuestionTest> list;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_question, null);
		viewpager = (ViewPager) view.findViewById(R.id.vp_question);
		handler = new Handler(new Handler.Callback() {

			@Override
			public boolean handleMessage(Message msg) {
				if (msg.what == 100) {
					result = (String) msg.obj;
					list = getData();
					if (list.size() > 0) {
						adapter = new MyQuestionAdapter(getActivity(), list);
						viewpager.setAdapter(adapter);
					}
				}
				return false;
			}
		});
		new MyThread(handler, url).start();
		return view;
	}

	public ArrayList<QuestionTest> getData() {
		ArrayList<QuestionTest> data = new ArrayList<>();
		try {
			JSONObject object = new JSONObject(result);
			if (object.has("data")) {
				JSONArray array = object.getJSONArray("data");
				for (int i = 0; i < array.length(); i++) {
					QuestionTest questionTest = new QuestionTest();
					JSONObject o = array.getJSONObject(i);
					if (o.has("title")) {
						String title = o.getString("title");
						questionTest.setTitle(title);
					}
					if (o.has("doubt")) {
						String doubt = o.getString("doubt");
						questionTest.setDoubt(doubt);
					}
					if (o.has("question")) {
						String question = o.getString("question");
						questionTest.setQuestion(question);
					}
					if (o.has("answer")) {
						String answer = o.getString("answer");
						questionTest.setAnswer(answer);
					}
					data.add(questionTest);

				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return data;
	}
}
